package com.df.my_net_game.game_rpc.codec;

import com.df.my_net_game.game_rpc.GRpcHeader;
import com.df.my_net_game.game_rpc.EzGameMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

public class GRpcCodec extends ByteToMessageCodec<EzGameMsg> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, EzGameMsg gRpcMsg, ByteBuf byteBuf) throws Exception {
        // 协议头结构：4字节魔数 + 4字节版本 + 4字节消息长度
//        byteBuf.writeInt(gRpcMsg.length())
//                .writeBytes(gRpcMsg.getHeader().tobytes())
//                .writeBytes(gRpcMsg.getBodyBytes());
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readByte()<4){
            return;
        }
        byteBuf.markReaderIndex();
        int len = byteBuf.readInt();
        if(byteBuf.readableBytes() < len-4){
            byteBuf.resetReaderIndex();
            return;
        }
        //todo 循环读一个消息长度进行解析
        EzGameMsg msg = new EzGameMsg();
        GRpcHeader header = new GRpcHeader();
        msg.setHeader(header);
        byte[] headerBytes = new byte[header.lenth()];
        byteBuf.readBytes(headerBytes);
        header.readFromBytes(headerBytes);

        byte[] bodyBytes = new byte[len-4-header.lenth()];
        msg.setBodyBytes(bodyBytes);

        list.add(msg);
    }
}
